﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KCMS.DataAcsess.Interfaces;
using StructureMap;
using AutoMapper;
using KCMS.BusinessLogic.Models;
using KCMS.BusinessLogic.Interfaces;


namespace KCMS.BusinessLogic.Engine
{
    public class OrderService : IOrderService
    {
        private IOrderManager orderManager = ObjectFactory.GetInstance<IOrderManager>();
        private ISettingsService settingsService = ObjectFactory.GetInstance<ISettingsService>();
        public Models.Order getById(Guid id)
        {
            DataAcsess.Entitys.OrderEntity orderEntity = orderManager.getById(id);
            return Mapper.Map<DataAcsess.Entitys.OrderEntity, Models.Order>(orderEntity);
        }

        public IEnumerable<Models.Order> getAll()
        {
            var model = from t in orderManager.getAll()
                        orderby t.Number descending
                        select t;
            return Mapper.Map<IEnumerable<DataAcsess.Entitys.OrderEntity>, IEnumerable<Models.Order>>(model);

        }

        public void update(Order order)
        {
            orderManager.update(Mapper.Map<Order, DataAcsess.Entitys.OrderEntity>(order));
        }


        public Guid save(Order order)
        {
            int maxNumber;

            var orders = (from t in getAll()
                          select t.Number).ToList();
            if (orders.Count() != 0)
            {
                maxNumber = orders.Max();
                maxNumber++;
            }
            else maxNumber = 1000;

            order.Number = maxNumber;
            return orderManager.save(Mapper.Map<Order, DataAcsess.Entitys.OrderEntity>(order));
        }


        public void delete(Guid id)
        {
            orderManager.delete(id);
        }



        Order IOrderService.getByNumber(int numberOfOrder)
        {
            var order = (from t in getAll()
                         where t.Number.Equals(numberOfOrder)
                         select t).SingleOrDefault();
            return order;
        }


        public bool ChekOrderTotal(Order order)
        {
            Settings settings = settingsService.getSettings();
            if (order.Total < settings.SaleMinimum)
                return false;
            else return true;
        }
    }
}
